package com.yuan.yblog.portal.controller;
import com.yuan.yblog.common.api.CommonResult;
import com.yuan.yblog.common.pojo.VerificationCodeImg;
import com.yuan.yblog.common.service.CaptchaService;
import com.yuan.yblog.common.service.RedisService;
import com.yuan.yblog.common.utils.StringUtils;
import com.yuan.yblog.portal.aop.annotation.Log;
import com.yuan.yblog.portal.aop.annotation.SlidingWindowLimiter;
import com.yuan.yblog.portal.enums.BusinessType;
import com.yuan.yblog.portal.enums.LimitType;
import com.yuan.yblog.portal.pojo.VO.UserLoginSuccessVO;
import com.yuan.yblog.portal.service.AuthenticationService;
import com.yuan.yblog.portal.service.UserService;
import com.yuan.yblog.security.util.JwtTokenUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Tag(name = "注册、登录、鉴权（auth）接口")
public class AuthController {
    @Autowired
    UserService userService;

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    RedisService redisService;

    @Autowired
    CaptchaService captchaService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @SlidingWindowLimiter(key = "auth", windowSize = 120, windowTimeRange = 60, limitType = LimitType.IP)
    @Operation(summary = "注册")
    @PostMapping("/register")
    public CommonResult<Integer> userRegister(
            @Parameter(description = "用户昵称") @RequestParam String username,
            @Parameter(description = "密码（明文）") @RequestParam String password,
            @Parameter(description = "邮箱") @RequestParam String email,
            @Parameter(description = "验证码标识") @RequestParam String captchaId,
            @Parameter(description = "验证码") @RequestParam String captcha){
        Boolean succeed = userService.register(username, password, email, captchaId, captcha);
        if (succeed) {
            return CommonResult.success(1,"注册成功");
        }
        return CommonResult.failed("注册失败");
    }

    @SlidingWindowLimiter(key = "auth", windowSize = 120, windowTimeRange = 60, limitType = LimitType.IP)
    @Operation(summary = "登录")
    @GetMapping("/login")
    public CommonResult<UserLoginSuccessVO> userLogin(
                @Parameter(description = "邮箱") @RequestParam String userEmail,
                @Parameter(description = "密码") @RequestParam String password){
        UserLoginSuccessVO userLoginSuccessVO = authenticationService.login(userEmail,password);
        return CommonResult.success(userLoginSuccessVO);
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @Operation(summary = "重置密码")
    @PutMapping("/auth/repass")
    public CommonResult<Integer> userRepass(
            @Parameter(description = "旧密码") @RequestParam(required = false) String oldPassword,
            @Parameter(description = "新密码") @RequestParam String newPassword,
            @Parameter(description = "数据库密文（一般不需要）") @RequestParam(required = false) String authentication
    ){
        Boolean flag = userService.updatePassword(oldPassword, newPassword, authentication);
        if(flag){
            return CommonResult.success(1,"操作成功");
        }
        return CommonResult.failed("操作失败");
    }


    @SlidingWindowLimiter(key = "auth", windowSize = 120, windowTimeRange = 60, limitType = LimitType.IP)
    @Operation(summary = "【获取】验证码图片，captchaId为空表示生成验证码，captchaId不空表示刷新验证码（不能刷新“已过期”的验证码）")
    @GetMapping("/getCaptcha")
    public CommonResult<VerificationCodeImg> getCaptcha(@Parameter(description = "验证码标识（空表示生成验证码，不空表示刷新验证码）") @RequestParam(required = false) String captchaId) {
        VerificationCodeImg img = null;
        if (!StringUtils.isEmpty(captchaId)) {
            // 更新验证码
            img = captchaService.refreshCaptcha(captchaId);
        } else {
            // 生成验证码
            img = captchaService.generateCaptcha();
        }
        return CommonResult.success(img);
    }

    @SlidingWindowLimiter(key = "auth", windowSize = 120, windowTimeRange = 60, limitType = LimitType.IP)
    @Operation(summary = "主动刷新token")
    @GetMapping("/refresh")
    public CommonResult<String> refreshToken(HttpServletRequest request) {
        String newToken = jwtTokenUtil.refreshHeadToken(jwtTokenUtil.getToken(request));
        return CommonResult.success(newToken,"刷新token成功");
    }

    @SlidingWindowLimiter(key = "captcha", windowSize = 120, windowTimeRange = 60, limitType = LimitType.IP)
    @Operation(summary = "【校验】验证码")
    @GetMapping("/verifyCaptcha")
    public CommonResult<String> verifyCaptcha(
            @Parameter(description = "验证码标识") @RequestParam String captchaId,
            @Parameter(description = "验证码") @RequestParam String captcha) {
        Boolean flag = captchaService.verifyCaptcha(captchaId,captcha);
        if(!flag) {
            return CommonResult.failed("验证码错误");
        }
        return CommonResult.success(captchaId,"验证码正确");
    }
}
